package com.ultimatech.webappdemo.authmgr.realm;

import com.ultimatech.webappdemo.authmgr.service.IAuthService;
import com.ultimatech.webappdemo.authmgr.service.IPasswordService;
import com.ultimatech.webappdemo.base.model.SysRole;
import com.ultimatech.webappdemo.base.model.SysUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Created by 张乐平 on 7/28 0028.
 */
@Component("myRealm")
public class MyRealm extends AuthorizingRealm {

    private Logger logger = LoggerFactory.getLogger(MyRealm.class);

    @Autowired
    public MyRealm(@Qualifier("shiroEncacheManager") CacheManager cacheManager) {
        super(cacheManager);
    }

    @Autowired
    private IPasswordService passwordService;

    @Autowired
    private IAuthService authService;

    public IAuthService getAuthService() {
        return authService;
    }

    public void setAuthService(IAuthService authService) {
        this.authService = authService;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Iterator itPrincipal = principalCollection.fromRealm(getName()).iterator();
        if (itPrincipal.hasNext()) {
            //获取登录时输入的用户名
            String loginName = (String) itPrincipal.next();
            //到数据库查是否有此对象
            SysUser user = this.getAuthService().getUserByLoginName(loginName);
            logger.debug("完成从数据库中获取用户信息");
            if (user != null) {
                //权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
                SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
                Set<String> rolenames = user.getRolesName();
                logger.debug("完成从数据库中获取用户角色");
                //用户的角色集合
                info.setRoles(rolenames);
                //用户的角色对应的所有权限，如果只使用角色定义访问权限，下面的四行可以不要
                List<SysRole> roleList = user.getRoleList();
                logger.debug("完成从数据库中获取用户角色列表。");
                for (SysRole role : roleList) {
                    List<String> permissionList = role.getPermissionsString();
                    logger.debug("完成获取其中一个角色的permission");
                    info.addStringPermissions(role.getPermissionsString());
                }
                return info;
            }
        } else {
            return null;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //UsernamePasswordToken对象用来存放提交的登录信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //查出是否有此用户
        SysUser user = this.getAuthService().getUserByLoginName(token.getUsername());
        if (user != null) {
            //若存在，将此用户存放到登录认证info中
            return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());
        }
        return null;
    }
}
